package felix.things.router.modbus.net;

import com.ghgande.j2mod.modbus.io.AbstractModbusTransport;
import com.ghgande.j2mod.modbus.io.ModbusRTUTransport;
import com.ghgande.j2mod.modbus.net.AbstractSerialConnection;
import com.ghgande.j2mod.modbus.net.SerialConnection;
import com.ghgande.j2mod.modbus.util.SerialParameters;
import felix.things.router.modbus.transport.RtuTransportConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Felix
 * @date 2019/10/30
 **/
@Component
@Slf4j
public class RtuModbusMasterFactory {

    public static AbstractModbusTransport createModbusTransport(RtuTransportConfiguration transportConfiguration) {
        /*
         * Create a ModbusSerialListener with the default Modbus values of
         * 19200 baud, no parity, using the specified device. If there is an
         * additional part after the device name, it will be used as the
         * Modbus unit number.
         */
        SerialParameters parms = new SerialParameters();
        parms.setPortName(transportConfiguration.getPortName());
        parms.setBaudRate(transportConfiguration.getBaudRate());
        parms.setDatabits(transportConfiguration.getDataBits());
        parms.setParity(transportConfiguration.getParity());
        parms.setStopbits(transportConfiguration.getStopBits());
        parms.setFlowControlIn(AbstractSerialConnection.FLOW_CONTROL_DISABLED);
        parms.setEcho(false);
        try {
            ModbusRTUTransport transport = new ModbusRTUTransport();
            transport.setCommPort(SerialConnection.getCommPort(parms.getPortName()));
            // transport.setCommPort(serialConnection);
            transport.setEcho(transportConfiguration.getEncoding());
            return transport;
        } catch (IOException e) {
            return null;
        }
    }
}
